<?php
//花呗支付
// 授权回调地址，将用户的UID与授权返回码存入
/*1、连接数据库 
        端口号或者地址 
        登录数据库的登录名
        登录密码
        要操作的数据库名
        */


if ($_POST) {
    $val = '---------------------POST异步通知----------------<br>';
    $val .= json_encode($_POST);
    $val .= $update;
    $val .= '-------------------------------------------------<br>';
} else {
    $val = '------------------------GET通知-------------------<br>';
    $val .= json_encode($_GET);
    $val .= '-------------------------------------------------<br>';
}

file_put_contents("hb.txt", $val, FILE_APPEND);


$link = mysqli_connect('127.0.0.1', 'ali', 'ali', 'ali', '3306');
if (!$link) {

}
//2、选择要操作的数据库
mysqli_select_db($link, 'ali');
//3、设置交互编码
mysqli_query($link, 'set names utf8');


//  花呗花呗花呗花呗花呗


// "trade_status":"WAIT_BUYER_PAY"

if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
    // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；3、将口碑商户扣取费率后的余额转入企业支付宝


    $danhao = $_POST['out_trade_no'];

    $select = "select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
    $arr = mysqli_query($link, $select);
    $one = mysqli_fetch_assoc($arr);

    if ($one['status'] == 1) {
        echo success;
    } else {
        $trade_no = $_POST['trade_no'];
        $buyer = $_POST['buyer_logon_id'];
        $seller = $_POST['seller_email'];
        $money = $_POST['total_amount'];
        $seller_id = $_POST['seller_id'];
        $buyer_id = $_POST['buyer_id'];
        // gather
        $uid = $one['uid'];
        $select = "select * from `jd_gather` where `uid`={$uid} limit 1";
        // $select="select * from `jd_kbsh` where `uid`=222";
        $arr = mysqli_query($link, $select);
        $_one = mysqli_fetch_assoc($arr);

        if ($one['hk'] == 1) {
            $yh_money = $money * (100 - $_one['up_set']) / 100;
        } else {
//            $yh_money   =$money*($_one['path6']-$_one['up_set'])/100;

            //修改为： 订单收益 = 订单金额 × （回款费率 - （上级设定费率+分额度累加费率））
            $levelRate = 0;
            if ($money >= 400 && $money < 600) {
                $levelRate = 0.4;
            } elseif ($money >= 600 && $money < 1000) {
                $levelRate = 0.4;
            } elseif ($money >= 1000) {
                $levelRate = 0.6;
            }
            $yh_money = $money * ($_one['path5'] - ($_one['up_set2'] + $levelRate)) / 100;
        }


        // 1、将订单状态修改为成功
        $update = "update `jd_dingdan` set `trade_no`='{$trade_no}',`buyer`='{$buyer}',`seller`='{$seller}',`seller_id`='{$seller_id}',`status`=1,`pay_money`={$money},`tx`=0,`yh_money`='{$yh_money}' where `danhao`='{$danhao}'";
        // UPDATE `jd_dingdan` SET `trade_no`='2017120821001004015319222317',`buyer`='173***3411',`seller`='nnxx***@162.com' WHERE `danhao`='20171208145556' ;
        $id1 = mysqli_query($link, $update);
        if ($id1 > 0) {
            // 2、修改平台用户的余额；


            if ($one['hk'] == 1) {
                $total = $_one['money'] + $money * (100 - $_one['up_set']) / 100;
            } else {
                $total = $_one['money'] + $money * ($_one['path6'] - $_one['up_set']) / 100;
            }
            $update = "update `jd_dingdan` set `t_money`='{$total}' where `danhao`='{$danhao}'";

            mysqli_query($link, $update);

            // $total=$_one['money']+$money*(1-$_one['path1']/100);  
            // 修改平台用户余额
            $update = "update `jd_gather` set `money`={$total} where `uid`={$uid}";
            $id2 = mysqli_query($link, $update);
            if ($id2 > 0) {

                if ($one['hk'] == 1) {
                    //不回款不需制定
                } else {
                    // 插播：制定对应的转账表
                    $trans_money = $money * (1 - $_one['path6'] / 100);
                    $out_biz_no = 'hb' . date("YmdHis") . rand(1000, 9999);
                    $add = "insert into `jd_trans` (`trade_no`,`uid`,`money`,`buyer_id`,`out_biz_no`) values ('{$trade_no}','{$uid}','{$trans_money}','{$buyer_id}','{$out_biz_no}')";
                    mysqli_query($link, $add);
                }


                // 3、制定分账信息  通过seller在口碑商户表中找到使用的授权令牌
                $add = "insert into jd_split (`seller_id`,`money_in`,`trade_no`) values ('{$seller_id}','{$money}','{$trade_no}')";
                $id3 = mysqli_query($link, $add);
                if ($id3 > 0) {



                    // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%


                    $select = "select * from `jd_ptyh` where `uid`={$one[uid]} limit 1";
                    $arr = mysqli_query($link, $select);
                    $one2 = mysqli_fetch_assoc($arr);  //当前用户

                    if ($one2['pid'] == 0 || $one2['pid'] == 1 || $one2['level'] > 4) {//没有上级或者4级以下
                        echo success;
                    } else {
                        // 查找上一级
                        /** 父级 start */
                        $select = "select * from `jd_ptyh` where `uid`={$one2[pid]} limit 1";
                        $arr = mysqli_query($link, $select);
                        $one3 = mysqli_fetch_assoc($arr);  //当前用户的上级


                        $shou = $one['uid'];
                        $parent = $one3['uid'];
                        $danhao = 'hb' . date("YmdHis") . rand(1000, 9999);
                        $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',1,1)";
                        $id4 = mysqli_query($link, $add);
                        /** 父级 end */

                        /** 爷爷级  start */
                        $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$one3[pid]} limit 1";
                        $grandfatherArr = mysqli_query($link, $grandfatherSql);
                        $grandfather = mysqli_fetch_assoc($grandfatherArr);
                        $grandfatherUid = $grandfather['uid'];
                        $grandfatherDividend = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',1,2)";
                        $grandfatherResult = mysqli_query($link, $grandfatherDividend);

                        if ($id4 > 0 && $grandfatherResult > 0) {

                            echo success;
                        } else {
                            echo fail;
                        }

                    }




                } else {
                    echo fail;
                }

            } else {
                echo fail;
            }
        } else {
            echo fail;
        }
    }
    
    
    

}









